package com.iterable.demo2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class ReversibleArrayList<T> extends ArrayList<T> {

	public ReversibleArrayList(Collection<T> c) {
		super(c);
	}

	public Iterable<T> reversed() {
		return new Iterable<T>() {

			@Override
			public Iterator<T> iterator() {
				return new Iterator<T>() {

					int index = size() - 1;

					@Override
					public boolean hasNext() {
						return index >= 0;
					}

					@Override
					public T next() {
						return get(index--);
					}

					@Override
					public void remove() {
						throw new UnsupportedOperationException();
					}

				};
			}

		};
	}

	public static void main(String[] args) {
		ReversibleArrayList<String> array = new ReversibleArrayList(
				Arrays.asList("my name is zhang su lei".split(" ")));
		for (String string : array) {
			System.out.println(string);
		}
		for (String string : array.reversed()) {
			System.out.println(string);
		}
	}

}
